/* clock example: countdown */

#include <stdio.h>
#include <iostream>
#include <time.h>
#include <math.h>
#include "Synchronizer.h"

double delta = 0.00025;

int compare(double a, double b) {
	//TODO: Qual a forma certa de comparar double quando há perda de precisão?
	double diff = (a - b) + delta;
	return (diff >= 0.001) ? 1 : (diff < 0) ? -1 : 0;
}

class Countdown: public Synchronizable {
	Synchronizer *_synchronizer;
	double _countdown; // em segundos
public:
	Countdown() {
		_countdown = 10;
	}
	void synchronizer(Synchronizer& synchronizer) {
		_synchronizer = &synchronizer;
	}
	void synch(double const& seconds_past) {
		if (_countdown == 10.0) {
			printf("Starting countdown...\n");
		}
		if (compare(_countdown, 0.0) == 0) {
			printf("FIRE!!!\n");
			_synchronizer->stop();
		} else if (compare(_countdown, floor(_countdown + delta)) == 0) {
			printf("%.0f\n", _countdown);
		}
		_countdown -= seconds_past;
	}
};

int main() {
	Countdown countdown;
	Synchronizer synchronizer(countdown);

	countdown.synchronizer(synchronizer);

	synchronizer.run();

	return 0;
}
